package com.yhsx.jenkins.d3.service;

import com.yhsx.jenkins.d3.pojo.Demo;
import com.yhsx.jenkins.d3.mapper.DemoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * 测试服务
 *
 * @author slf
 * @since 2024/5/10 9:02
 **/
@Service
public class DemoService {
    Logger log = LoggerFactory.getLogger(DemoService.class);

    public Demo get(String id) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("端口：{}",request.getServerPort());
        if (id == null)
        {
            return null;
        }
        return DemoMapper.DEMO_DATA.stream().filter(e->id.equals(e.getId())).findFirst().orElse(null);
    }

    public Demo insert(Demo demo) {
        Demo old = get(demo.getId());
        if (old!=null){
            log.warn("用户已存在，id:{}",demo.getId());
            return null;
        }

        if (demo.getId()==null){
            demo.setId(UUID.randomUUID().toString());
        }
        DemoMapper.DEMO_DATA.add(demo);
        log.info("用户添加成功:{}",demo);
        return demo;
    }

    public Demo update(Demo demo) {
        Demo old = get(demo.getId());
        if (old==null){
            log.warn("用户不存在，id:{}",demo.getId());
            return null;
        }

        old.setName(demo.getName());
        old.setAge(demo.getAge());
        log.info("用户更新成功:{}",old);
        return old;
    }

    public Demo del(String id) {
        Demo old = get(id);
        if (old==null){
            log.warn("用户不存在，id:{}",id);
            return null;
        }
        DemoMapper.DEMO_DATA.remove(old);
        log.info("用户删除成功:{}",old);
        return old;
    }
}
